package com.lbb.sqlsession;

import com.lbb.config.BoundSql;
import com.lbb.pojo.Configuration;
import com.lbb.pojo.MappedStatement;
import com.lbb.util.GenericTokenParser;
import com.lbb.util.ParameterMappingTokenHandler;
import com.lbb.util.ParamterMapping;


import java.beans.MethodDescriptor;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor{
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object...params) throws Exception{
        //1.连接池获取链接
        Connection connection = configuration.getDataSource().getConnection();
        //2.获取sql语句，将sql语句中的#{}进行解析
        String sql = mappedStatement.getSql();
        //BoundSql将解析后的sql语句和参数进行打包，例如：
        //select * from user where id=#{id}解析为select * from user where id=?和参数id
        BoundSql boundSql = getBoundSql(sql);


        //3.产生预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        List<ParamterMapping> paramterMappingList = boundSql.getParamterMappingList();
        //4.处理传入参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = getTypeClass(paramterType);

        for(int i = 0; i < paramterMappingList.size();i++){
            ParamterMapping paramterMapping = paramterMappingList.get(i);
            String content = paramterMapping.getContent();

            //利用反射获取用户传进来的具体参数值
            Field field = paramterTypeClass.getDeclaredField(content);
            //将对应字段的访问权限变更为public
            field.setAccessible(true);
            //获取传入的值
            Object o = field.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }

        //5.执行sql语句
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getTypeClass(resultType);

        ArrayList<Object> arrayList = new ArrayList<>();
        //6.封装结果
        while(resultSet.next()){
            Object o = resultTypeClass.getDeclaredConstructor().newInstance();
            ResultSetMetaData resultSetMetaData= resultSet.getMetaData();
            for(int i = 1; i <= resultSetMetaData.getColumnCount();i++){
                String columnName = resultSetMetaData.getColumnName(i);
                Object columnValue = resultSet.getObject(columnName);

                //使用内省，根据数据库和pojo的对应关系，封装数据
                //内省： Java JDK中提供了一套 API 用来访问某个属性的 getter/setter 方法，这就是内省,针对javabean。
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method method = propertyDescriptor.getWriteMethod();
                method.invoke(o,columnValue);
            }
            arrayList.add(o);

        }
        return (List<E>) arrayList;
    }

    private Class<?> getTypeClass(String paramterType) throws ClassNotFoundException {
        if(paramterType != null){
            Class<?> paramTypeClass = Class.forName(paramterType);
            return paramTypeClass;
        }
        return null;
    }

    //实现解析sql语句中的#{}
    private BoundSql getBoundSql(String sql){
        ParameterMappingTokenHandler parameterMappingTokenHandler =
                new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser =
                new GenericTokenParser("#{","}",parameterMappingTokenHandler);
        String sqlText = genericTokenParser.parse(sql);
        List<ParamterMapping> paramterMappings = parameterMappingTokenHandler.getParameterMappings();


        BoundSql boundSql = new BoundSql(sqlText,paramterMappings);
        return boundSql;
    }

    public int update(Configuration configuration, MappedStatement mappedStatement, Object[] params) throws Exception {
        //1.获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.获取sql语句并解析
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        //3.产生预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        List<ParamterMapping> paramterMappingList = boundSql.getParamterMappingList();
        //4.处理传出参数
        String paramterType = mappedStatement.getParamterType();
        Class<?> paramterTypeClass = Class.forName(paramterType);
        for(int i = 0; i < paramterMappingList.size();i++){
            ParamterMapping paramterMapping = paramterMappingList.get(i);
            String content = paramterMapping.getContent();

            Field field = paramterTypeClass.getDeclaredField(content);
            field.setAccessible(true);
            Object o = field.get(params[0]);
            preparedStatement.setObject(i+1,o);
        }
        //5.执行sql
        int result = preparedStatement.executeUpdate();
        //6.封装结果
        return result;
    }
}
